package com.xuce.controller;

import com.xuce.constant.RedisConstant;
import com.xuce.dto.ResultBean;
import com.xuce.pojo.TUser;
import com.xuce.service.IUserService;
import com.xuce.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 徐策
 * @date 2020/3/11 16:36
 */
@RestController
@RequestMapping("user")
@Scope("prototype")
public class UserController {

    @Autowired
    private IUserService service;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate redisTemplate;


//    @RequestMapping("register/email/{addr}/{password}")
    @PostMapping("register/email")
    public ResultBean registerByEmail(@RequestBody TUser user){
        //1.生成uuid
        String uuid = UUID.randomUUID().toString();
        //2.发邮件  通过ribbon来调用

        String addr = user.getEmail();
        String password = user.getPassword();

        String url = String.format("http://email-service/email/send/%s/%s", addr, uuid);
        ResultBean resultBean = restTemplate.getForObject(url, ResultBean.class);
        ResultBean result = null;
        if(resultBean.getErrno()==0){
            //3.url组织好的键值对存到redis中
            //往redis中存入这样的键值对： regist:email:url:128731-sdfl-123 = addr
            redisTemplate.opsForValue().set(RedisUtil.getRedisKey(RedisConstant.REGIST_EMAIL_URL_KEY_PRE,uuid),addr,15, TimeUnit.MINUTES);
            //4.去数据库中创建该用户
//            result = restTemplate.getForObject(String.format("http://USER-SERVICE/user/register/%s/%s", addr, password), ResultBean.class);
           return service.register(addr,password);
        }
//user-service
        return result;
    }

    @RequestMapping("register")
    public ResultBean register(@RequestParam String uname, @RequestParam String password){
        return  service.register(uname,password);
//        return ResultBean.success("注册成功");
    }


}
